const socialType = 34; // 社交类型 - 微信小程序

import socialLogin from "@/sheep/api/member/auth.js"

const login = () => {
	return new Promise((resolve) => {
		const token = getAccessToken();
		if (token) return resolve("ok")

		uni.login({
			provider: 'weixin',
			onlyAuthorize: true,
			success(loginRes) {
				if (loginRes.errMsg === "login:ok") {
					socialLogin.socialLogin(socialType, loginRes.code, 'default').then(res => {
						if (res.code === 0) {
							setToken(res.data.accessToken)
							setOpenid(res.data.openid)
							setRefreshToken(res.data.refreshToken)
							resolve("ok")
						} else errToast()
					})
				} else errToast()
			}
		})
	})
}

/** 获得访问令牌 */
const getAccessToken = () => {
  return uni.getStorageSync('token');
}

const setToken = (token) => {
	uni.setStorageSync('token', token);
}

const setRefreshToken = (refreshToken) => {
	uni.setStorageSync('refresh-token', refreshToken);
}

const setOpenid = (openid) => {
	uni.setStorageSync('openid', openid);
}

const errToast = () => {
	uni.showToast({
		title: '登录失败，请重试',
		icon: "none"
	})
}

export default login